<template>
	<view class="container">
		<steps 
			typeCode="JiaBan" 
			:brief="brief" 
			:notEmpty="checkBukaFiled" 
			:disabled="disabled"
			:checkResult="checkResult"
			:insflowid="insflowid"
			@confirm="confirm">
			<view class="container__list">
				<view class="hover" hover-class="clickable" @click="goSelectUserPage">
					<view class="container__list--text">
						<text class="container__list--text-symbol">*</text>
						<text class="container__list--text-des">加班人</text>
					</view>
					<view class="container__list--value">
						<view class="container__list--value-user" v-for="item in compUsers">
							{{item.pname}}
						</view>
						<view class="container__list--value-info" v-show="users.length > 3">等{{users.length}}人</view>
					</view>
					<view class="container__list--icon">
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>
				</view>
			</view>
			<view class="container__list">
				<view class="hover" hover-class="clickable">
					<view class="container__list--text">
						<text class="container__list--text-symbol">*</text>
						<text class="container__list--text-des">开始时间</text>
					</view>
					<view class="container__list--time">
						<view class="container__list--time-text" @click="startShow">
							<text v-if="!startDateTime">请选择</text>
							<text v-else>{{startDateTime}}</text>
						</view>
					</view>
					<view class="container__list--icon">
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>
				</view>
			</view>
			<view class="container__list">
				<view class="hover" hover-class="clickable">
					<view class="container__list--text">
						<text class="container__list--text-symbol">*</text>
						<text class="container__list--text-des">结束时间</text>
					</view>
					<view class="container__list--time">
						<view class="container__list--time-text" @click="endShow">
							<text v-if="!endDateTime">请选择</text>
							<text v-else>{{endDateTime}}</text>
						</view>
					</view>
					<view class="container__list--icon">
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>
				</view>
			</view>
			<view class="container__detail" v-show="dates.length && hoursDisabled">
				<view class="container__detail--title">为了方便统计，请填写每日加班时长</view>
				<view class="container__detail--head">
					<view class="">
						<text class="container__list--text-symbol">*</text>
						<text class="container__list--text-des">加班时间</text>
					</view>
					<view class="">
						<text class="container__list--text-symbol">*</text>
						<text class="container__list--text-des">(小时)</text>
					</view>
				</view>
				<view class="container__detail--item" v-for="item in dates">
					<view class="">{{item.date}}</view>
					<view class="">
						<input type="number" v-model="item.hour" :maxlength="3" @input="calcHours"/>
					</view>
				</view>
			</view>
			<view class="container__list" style="padding: 10rpx 20rpx;">
				<view class="container__list--text">
					<text class="container__list--text-symbol">*</text>
					<text class="container__list--text-des">总时长(小时)</text>
				</view>
				<view class="container__list--textarea">
					<input type="number" v-model="hours" :disabled="hoursDisabled" @blur="checkHours"/>
				</view>
			</view>
			<view class="container__list" style="padding: 10rpx 20rpx;">
				<view class="container__list--text">
					<text class="container__list--text-des">加班原因</text>
				</view>
				<view class="container__list--textarea">
					<input type="text" v-model="content" placeholder="请输入" placeholder-style="font-size: 27rpx;color: #aaa;" />
				</view>
			</view>
		</steps>
		<datetime-picker ref="startDateTime" type="datetime" :border="false" returnType="date" v-model="startTime" hide-second @change="confirmStartDateTime" />
		<datetime-picker ref="endDateTime" type="datetime" :border="false" returnType="date" v-model="endTime" hide-second @change="confirmEndDateTime" />
	</view>
</template>

<script>
	import Steps from '@/pages/home/child/add-attend-apply/components/steps.vue'
	import _custom from '@/common/_custom.js'
	import _data from '@/common/_data.js'
	import moment from 'moment'
	import DatetimePicker from '@/components/custom/datetime-picker/uni-datetime-picker.vue'
	
	export default {
		components: {
			Steps,
			DatetimePicker
		},
		data() {
			return {
				obsusername: _data.localData('name'),
				pxid: _data.localData('userid'),
				static_avator: _data.data('static_url'),
				startTime: '',
				endTime: '',
				startDateTime: '',
				endDateTime: '',
				content: '',
				list: [],
				users: [],//加班人
				hours: 0,
				dates: [],
				hoursDisabled: false,//是否为同一天
				disabled: true,
				checkResult: '',
				data: {},
				insflowid: ''
			}
		},
		onLoad(options) {
			let that = this;
			if(options.data) {
				this.data = JSON.parse(options.data)
				if(!this.data.length) return
				console.log(this.data)
				this.insflowid = options.insflowid;
				this.startDateTime = this.data[0].StartTime;
				this.startTime = this.data[0].StartTime;
				this.endDateTime = this.data[0].EndTime;
				this.endTime = this.data[0].EndTime;
				this.calDateTime();
				this.dates = [];
				let hours = 0;
				this.data.forEach(item => {
					this.dates.push({
						date: item.ExtraDate,
						hour: item.ExtraHours
					})
					hours += item.ExtraHours*1
				})
				this.checkForm();
				if(!this.hoursDisabled) {
					this.hours = hours;
				}
				this.content = this.data[0].Reason;
				let users = this.data[0].UserName.split(',');
				let pxid = this.data[0].Pxid.split(',');
				this.users = users.map((item,index) => {
					return {
						pname: item,
						pxid: pxid[index],
						avator: this.static_avator + "/static/photo/user/" + pxid[index] + "/70.jpg",
					}
				})
				this.checkForm();
			} else {
				this.users.unshift({
					pname: this.obsusername,
					avator: this.static_avator + "/static/photo/user/" + this.pxid + "/70.jpg",
					pxid: this.pxid
				})
			}
			_data.localData('select-list-extra',this.users);
			uni.$on('select-list-extra',v => {
				this.users = v;
				_data.localData('select-list-extra',this.users);
			})
		},
		onUnload() {
			_data.localData('select-list-extra',[]);
			uni.$off('select-list-extra');
		},
		computed: {
			brief() {
				let user = '';
				if(Object.prototype.toString.call(this.users) == '[object Array]') {
					this.users.forEach((item,index) =>{
						if(index != this.users.length) {
							user += (item.pname + ' ')
						} else {
							user += item.pname
						}
					})
					if(user.length>10) {
						user = user.substring(0,10) + '...'
					}
				}
				return '加班人：' + user + '|' +'开始时间：' + this.startDateTime + '|' + '结束时间：' + this.endDateTime
			},
			checkBukaFiled() {
				let flag = true;
				this.dates.forEach(item => {
					if(!item.hour) flag = false
				})
				return this.users.length && this.startDateTime && this.endDateTime && flag ? true : false;
			},
			compUsers() {
				return this.users.length > 3 ? this.users.slice(0,3) : this.users
			}
		},
		methods: {
			startShow() {
				this.startTime = this.startTime ? moment(this.startTime).format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm') + ':00'
				this.startDateTime = this.startTime;
				this.checkForm();
				this.$refs.startDateTime.show()
			},
			endShow() {
				this.endTime = this.endTime ? moment(this.endTime).format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm') + ':00'
				this.endDateTime = this.endTime;
				this.checkForm();
				this.$refs.endDateTime.show()
			},
			confirmStartDateTime(e) {
				this.startDateTime = moment(e).format('YYYY-MM-DD HH:mm:ss');
				this.calDateTime();
				this.checkForm();
			},
			confirmEndDateTime(e) {
				this.endDateTime = moment(e).format('YYYY-MM-DD HH:mm:ss');
				this.calDateTime();
				this.checkForm();
			},
			/**
			 * 计算开始时间和结束时间
			 */
			calDateTime() {
				if(!this.startDateTime || !this.endDateTime) return
				this.hoursDisabled = false;
				this.dates = [];
				let dayDiff = moment(this.endDateTime).diff(this.startDateTime,'days');
				let hourDiff = moment(this.endDateTime).diff(this.startDateTime,'hour');
				if(hourDiff < 0) {
					this.disabled = true;
					this.checkResult = '结束时间不得早于开始时间';
				}
				let sDate = moment(this.startDateTime).format('YYYY-MM-DD');
				let eDate = moment(this.endDateTime).format('YYYY-MM-DD');
				if(dayDiff >= 1 || (dayDiff == 0 && sDate != eDate)) {
					this.hoursDisabled = true;
					let dates = this.enumerateDaysBetweenDates(sDate,eDate);
					this.dates = dates.map(item =>{
						return {
							date: item,
							hour: ''
						}
					})
				}
			},
			/**
			 * 获取两个日期之间的所有日期(已经保证了startDate 小于endDate，且二者不相等)
			 * @param {Object} startDate
			 * @param {Object} endDate
			 */
			enumerateDaysBetweenDates(startDate, endDate) {
				let daysList = [];
				let SDate = moment(startDate);
				let EDate = moment(endDate);
				daysList.push(SDate.format("YYYY-MM-DD"));
				while( SDate.add(1,"days").isBefore( EDate) ){
					daysList.push(SDate.format("YYYY-MM-DD"));
				}
				daysList.push(EDate.format("YYYY-MM-DD"));
				return daysList;
			},
			/**
			 * 校验每一天的小时数
			 */
			calcHours(e) {
				this.checkForm();
			},
			/**
			 * 校验输入的总时长
			 * @param {Object} apiparam
			 */
			checkHours(e) {
				this.hours = e.detail.value;
				this.checkForm();
			},
			/**
			 * 表单校验
			 */
			checkForm() {
				if(!this.startDateTime || !this.endDateTime) return
				if(this.hoursDisabled) {//非同一天
					let hours = 0;
					this.dates.forEach(item => {
						if(item.hour) hours += item.hour*1
					})
					this.hours = hours;
					for(let i = 0;i < this.dates.length;i++) {
						let hour = this.dates[i].hour;
						if(hour*1 <= 0 || hour*1 >= 24) {
							this.disabled = true;
							this.checkResult = '必须介于0到24之间';
							return;
						}
						let decimal = hour.split('.');
						let decimalLength = decimal.length > 1 ? decimal[1].length : 0;
						if(decimalLength > 1) {
							this.disabled = true;
							this.checkResult = '不能超过1位小数';
							return;
						}
					}
					this.disabled = false;
				} else {
					this.hours = this.hours + '';
					let decimal = this.hours.split('.');
					let decimalLength = decimal.length > 1 ? decimal[1].length : 0;
					if(this.hours*1 <= 0) {//总时长小于等于0
						this.disabled = true;
						this.checkResult = '加班总时长必须为正数'
						return
					}
					if(decimalLength > 1) {
						this.disabled = true;
						this.checkResult = '总时长不能超过1位小数';
						return
					}
					let endTime = moment(this.startDateTime).add(this.hours, 'h');//开始时间加总时长后的时间t
					let diff = moment(endTime).diff(this.endDateTime,'m');//t和结束时间之间的分钟数
					if(diff > 0) {//开始时间加总时长大于结束时间
						this.disabled = true;
						this.checkResult = '加班时长超过时间范围';
						return
					}
					this.disabled = false;
				}
				
			},
			/**
			 * 添加加班申请
			 * @param {Object} apiparam  接口参数
			 */
			extraAttendApply(apiparam) {
				return new Promise((resolve,reject) => {
					_custom.getDataJava({
						apiname: 'extraAttendApply',
						code: 3,
						apiparam,
						success(res) {
							resolve()
						}
					})
				})
			},
			/**
			 * 添加加班详情信息
			 * @param {Object} apiparam  接口参数
			 */
			extraAttendDetail(apiparam) {
				return new Promise((resolve,reject) => {
					_custom.getDataJava({
						apiname: 'extraAttendDetail',
						code: 13,
						apiparam,
						success(res) {
							resolve()
						}
					})
				})
			},
			/**
			 * 触发流程环节通知
			 */
			trigFlowStepNotice(apiparam) {
				let that = this;
				return new Promise((resolve,reject) => {
					_custom.getDataJava({
						apiname: 'trigFlowStepNotice',
						code: 2,
						apiparam,
						success() {
							resolve()
						}
					})
				})
			},
			/**
			 * 点击提交按钮申请流程后的回调
			 * @param {Object} v 回调参数
			 */
			confirm(v) {
				this.extraAttendApply({
					obsusername: this.obsusername,
					insflowid: v.insflowid,
					reason: this.content,
					starttime: this.startDateTime,
					endtime: this.endDateTime
				}).then(() => {
					let params = []
					if(this.dates.length) {
						this.users.forEach(item => {
							this.dates.forEach(value => {
								params.push({
									obsusername: this.obsusername,
									insflowid: v.insflowid,
									username: item.pname,
									pxid: item.pxid,
									extradate: value.date,
									extrahours: value.hour
								}) 
							})
						})
					} else {
						this.users.forEach(item => {
							params.push({
								obsusername: this.obsusername,
								insflowid: v.insflowid,
								username: item.pname,
								pxid: item.pxid,
								extradate: moment(this.startDateTime).format('YYYY-MM-DD'),
								extrahours: this.hours
							}) 
						})
					}
					return  this.extraAttendDetail(params)
				}).then(() =>{
					uni.showToast({
						title: '流程创建成功',
						icon: 'none'
					})
					this.trigFlowStepNotice({
						insflowid: v.insflowid,
					})
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/home/child/extra-attend/index?data=' + JSON.stringify(v)
						})
					},500)
				})
				
			},
			/**
			 * 跳转选人页面
			 */
			goSelectUserPage() {
				uni.navigateTo({
					url: '/pages/wait/add/select?name=extra'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		overflow-x: hidden;
		padding-bottom: 90rpx;
		
		&__list {
			background-color: #fff;
			margin-top: 30rpx;
			position: relative;
			
			&--text {
				
				&-symbol {
					color: red;
					margin: 0 5rpx;
				}
				
				&-des {
					font-size: 30rpx;
				}
				
			}
			
			&--time {
				font-size: 32rpx;
				color: #aaa;
				margin-left: 20rpx;
				position: relative;
				height: 60rpx;
			}
			
			&--textarea {
				margin-left: 20rpx;
				font-size: 32rpx;
			}
			
			&--icon {
				position: absolute;
				right: 20rpx;
				top: 50%;
				transform: translateY(-50%);
				z-index: 9;
			}
			
			&--value {
				display: flex;
				
				&-user {
					margin-right: 20rpx;
				}
			}
		}
		
		&__detail {
			
			&--title {
				font-size: 27rpx;
				line-height: 60rpx;
				padding-left: 20rpx;
			}
			
			&--head,&--item {
				margin: 0 40rpx;
				margin-bottom: 20rpx;
				background-color: #fff;
				display: flex;
				align-items: center;
				border-radius: 5rpx;
				height: 80rpx;
				
				view {
					flex: 1;
					padding-left: 20rpx;
					font-size: 27rpx;
					
					&:first-child {
						border-right: 1rpx solid #eee;
					}
				}
			}
			
			&--item {
				color: #aaa;
				
			}
		}
		
	}
	
	.flex {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		box-sizing: border-box;
	}
	
	.hover {
		padding: 10rpx 20rpx;
	}
</style>
